package main

import (
	"context"
	"fmt"
	"github.com/gin-gonic/gin"
	_ "github.com/honwee/awm/docs" // 导入swagger文档
	"github.com/honwee/awm/internal/api/router"
	"github.com/honwee/awm/internal/repository"
	"github.com/honwee/awm/internal/service"
	"github.com/honwee/awm/internal/zeromq"
	"github.com/honwee/awm/pkg/config"
	"github.com/honwee/awm/pkg/database"
	"github.com/honwee/awm/pkg/logger"
	"net/http"
	"os"
	"os/signal"
	"syscall"
	"time"
)

// @title AWM API
// @version 1.0
// @description AWM (Argo Workflow Monitor) API 服务

// @contact.name API Support
// @contact.url https://github.com/honwee/awm
// @contact.email honwee@163.com

// @license.name Apache 2.0
// @license.url http://www.apache.org/licenses/LICENSE-2.0.html

// @host localhost:8080
// @BasePath /api/v1
// @schemes http https

// @securityDefinitions.apikey ApiKeyAuth
// @in header
// @name Authorization
// @description API Key认证，格式：Bearer {API Key}
func main() {
	// 初始化配置
	if err := config.Init(); err != nil {
		panic(fmt.Sprintf("Failed to initialize config: %v", err))
	}

	// 初始化日志
	if err := logger.Init(); err != nil {
		panic(fmt.Sprintf("Failed to initialize logger: %v", err))
	}
	defer logger.Logger.Sync()

	log := logger.Logger.Sugar()

	// 初始化数据库连接
	if err := database.Init(); err != nil {
		log.Fatalf("Failed to initialize database: %v", err)
	}

	// 初始化仓库
	traceRepo := repository.NewTraceRepository()
	workflowRunRepo := repository.NewWorkflowRunRepository()
	projectUserRepo := repository.NewProjectUserRepository()

	// 初始化服务
	traceService := service.NewTraceService(traceRepo)
	workflowRunService := service.NewWorkflowRunService(workflowRunRepo)
	projectUserService := service.NewProjectUserService(projectUserRepo)

	// 初始化ZeroMQ服务器
	zmqServer, err := zeromq.NewServer(traceRepo, workflowRunRepo)
	if err != nil {
		log.Fatalf("Failed to create ZeroMQ server: %v", err)
	}

	// 启动ZeroMQ服务器
	if err := zmqServer.Start(); err != nil {
		log.Fatalf("Failed to start ZeroMQ server: %v", err)
	}
	defer zmqServer.Stop()

	// 初始化Gin引擎
	gin.SetMode(config.GlobalConfig.Server.Mode)
	engine := gin.New()

	// 使用gin中间件
	engine.Use(gin.Recovery())

	// 设置路由
	r := router.NewRouter(engine, traceService, workflowRunService, projectUserService)
	r.Setup()

	// 创建HTTP服务器
	srv := &http.Server{
		Addr:    fmt.Sprintf("%s:%d", config.GlobalConfig.Server.Host, config.GlobalConfig.Server.Port),
		Handler: engine,
	}

	// 优雅退出
	quit := make(chan os.Signal, 1)
	signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)

	go func() {
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("Failed to start server: %v", err)
		}
	}()

	log.Infof("Server started on %s:%d", config.GlobalConfig.Server.Host, config.GlobalConfig.Server.Port)

	<-quit
	log.Info("Shutting down server...")

	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer cancel()

	if err := srv.Shutdown(ctx); err != nil {
		log.Fatalf("Server forced to shutdown: %v", err)
	}

	log.Info("Server exited")
}
